import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yi_shop/model/product.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class BrandInfoController extends GetxController {
  RxList<NewProductModel> pageList = RxList([]);

  late ScrollController scrollController;

  int total = 35;

  RxBool isLoading = false.obs;

  RxBool hasNext = true.obs;

  RxBool isFollow = false.obs;

  @override
  void onInit() {
    scrollController = ScrollController()
      ..addListener(() {
        if (hasNext.isTrue &&
            isLoading.isFalse &&
            scrollController.offset >= scrollController.position.maxScrollExtent) {
          isLoading.value = true;
          loadMoreData();
        }
      });
    initData();
    super.onInit();
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }

  void initData() {
    var data = [
      NewProductModel(
          imgUrl:
              'https://gw.alicdn.com/imgextra/i3/369979583/O1CN01qux1e32Kf4Pov0iCR_!!369979583.jpg_Q75.jpg_.webp',
          name: '遥遥领先',
          price: 2999),
      NewProductModel(
          imgUrl:
              'https://img.alicdn.com/img/i1/96812084/O1CN01h21jMo1RGWI2PAmyg_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
          name: 'ipHone 13',
          price: 2899),
      NewProductModel(
          imgUrl:
              'https://img.alicdn.com/img/i2/2211596014329/O1CN01zmVkmr1hqjUo5CGey_!!2211596014329-0-alimamacc.jpg_360x360xzq75.jpg_.webp',
          name: '红点',
          price: 399),
      NewProductModel(
          imgUrl:
              'https://img.alicdn.com/img/i1/109702118/O1CN019jvBYL1RW5mm9g6Sf_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
          name: '小黑',
          price: 1999),
      NewProductModel(
          imgUrl:
              'https://gw.alicdn.com/imgextra/i4/1879944864/O1CN01ZKXBpx1lnlLcLnxN7_!!1879944864.jpg_Q75.jpg_.webp',
          name: 'Mate40Pro',
          price: 3999),
      NewProductModel(
          imgUrl:
              'https://gw.alicdn.com/imgextra/i3/1959202531/O1CN01brIKy11UZFL2cy4Qv_!!1959202531.jpg_Q75.jpg_.webp',
          name: 'DOOV朵唯H8超薄',
          price: 499),
      NewProductModel(
          imgUrl:
              'https://gw.alicdn.com/imgextra/i3/2783679443/O1CN01k3LNwj2Jcwu2Yx55c_!!2783679443.jpg_Q75.jpg_.webp',
          name: 'VIVO iQOO',
          price: 2999),
      NewProductModel(
          imgUrl:
              'https://gw.alicdn.com/imgextra/i4/2211621917396/O1CN01Bpsdjt24VQ3YPdI6N_!!2211621917396.jpg_Q75.jpg_.webp',
          name: '飞利-老人机',
          price: 199)
    ];
    pageList.addAll(data);
  }

  void loadMoreData() {
    Future.delayed(const Duration(seconds: 3), () {
      isLoading.value = false;
      if (pageList.length < total) {
        hasNext.value = true;
        initData();
        return;
      }
      hasNext.value = false;
    });
  }
}

class BrandInfoPage extends GetView<BrandInfoController> {
  const BrandInfoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: controller.scrollController,
        slivers: [
          SliverAppBar(
            leading: ToolsUtils.builderLeading(),
            actions: const [
              IconButton(
                  onPressed: ToolsUtils.openShare,
                  icon: Icon(
                    Icons.share_outlined,
                    size: 25,
                    weight: 900,
                    color: Colors.white,
                  ))
            ],
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              background: Stack(
                children: [
                  Container(
                    decoration: BoxDecoration(
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
                    alignment: Alignment.center,
                    child: SvgUtils.assetName('u110', width: 80, height: 60),
                  ),
                  Positioned(
                      right: 10,
                      bottom: 10,
                      child: TextButton(
                          onPressed: () {},
                          style: ButtonStyle(
                              backgroundColor: const MaterialStatePropertyAll(Colors.white),
                              // fixedSize: const MaterialStatePropertyAll(Size(90, 30)),
                              minimumSize: const MaterialStatePropertyAll(Size(90, 30)),
                              shape: MaterialStatePropertyAll(
                                  RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))),
                              padding: const MaterialStatePropertyAll(EdgeInsets.zero),
                              alignment: Alignment.center),
                          child: Text(
                            '制造商直供',
                            style: StylesUtils.customTextStyle(
                              color: ColorsUtils.colorF048,
                              fontSize: StylesUtils.fontSize12,
                            ),
                          )))
                ],
              ),
            ),
            expandedHeight: 187,
          ),
          SliverToBoxAdapter(
            child: Container(
              height: 220,
              color: Colors.white,
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.only(top: 15),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(left: 15.w, right: 10.w),
                          child: CachedNetworkImage(
                            imageUrl:
                                'https://img0.baidu.com/it/u=1443978623,730493301&fm=253&fmt=auto&app=138&f=JPEG?w=466&h=466',
                            width: 70,
                            height: 70,
                            fit: BoxFit.fill,
                          ),
                        ),
                        Expanded(
                            child: Column(
                          children: [
                            Container(
                              alignment: Alignment.center,
                              child: Text(
                                '华为',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.color6666,
                                    fontSize: StylesUtils.fontSize13,
                                    fontWeight: FontWeight.w700),
                              ),
                            ),
                            Container(
                              margin: const EdgeInsets.only(top: 15),
                              alignment: Alignment.center,
                              child: Text(
                                '国际著名软硬件提供商',
                                style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color9999,
                                  fontSize: StylesUtils.fontSize13,
                                ),
                              ),
                            ),
                            Container(
                              alignment: Alignment.center,
                              margin: const EdgeInsets.only(top: 10),
                              child: Wrap(
                                spacing: 10,
                                crossAxisAlignment: WrapCrossAlignment.center,
                                alignment: WrapAlignment.center,
                                children: [
                                  Icon(
                                    Icons.location_city,
                                    color:
                                        ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                                    size: 20,
                                  ),
                                  Text(
                                    '中国',
                                    style: StylesUtils.customTextStyle(
                                        fontSize: StylesUtils.fontSize12,
                                        color: ColorsUtils.color9999),
                                  ),
                                  Icon(
                                    Icons.heart_broken_sharp,
                                    size: 20,
                                    color:
                                        ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                                  ),
                                  Text(
                                    '5000',
                                    style: StylesUtils.customTextStyle(
                                        fontSize: StylesUtils.fontSize12,
                                        color: ColorsUtils.color9999),
                                  )
                                ],
                              ),
                            ),
                          ],
                        )),
                        Container(
                          padding: EdgeInsets.only(right: 15.w),
                          margin: const EdgeInsets.only(top: 20),
                          alignment: Alignment.center,
                          child: Obx(() => TextButton(
                              onPressed: () {
                                controller.isFollow.value = !controller.isFollow.value;
                              },
                              style: ButtonStyle(
                                  maximumSize: const MaterialStatePropertyAll(Size(80, 30)),
                                  fixedSize: const MaterialStatePropertyAll(Size(80, 30)),
                                  padding: const MaterialStatePropertyAll(EdgeInsets.zero),
                                  minimumSize: const MaterialStatePropertyAll(Size(80, 30)),
                                  backgroundColor: MaterialStatePropertyAll(activeBgColor),
                                  shape: MaterialStatePropertyAll(RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(
                                          controller.isFollow.isTrue ? 5 : 15))),
                                  side: MaterialStatePropertyAll(BorderSide(
                                    color: ColorsUtils.rgba(128, 128, 255, 1),
                                    width: controller.isFollow.isTrue ? 1 : 0,
                                  )),
                                  alignment: Alignment.center),
                              child: Text(
                                '${controller.isFollow.isTrue ? '√' : '+'}关注',
                                style: activeStyle,
                              ))),
                        )
                      ],
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 20.h),
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: Text(
                      '华为创立于1987年，是全球领先的ICT（信息与通信）基础设施和智能终端提供商。我们的20.7万员工遍及170多个国家和地区，为全球30多亿人口提供服务。我们致力于把数字世界带入每个人、每个家庭、每个组织，构建万物互联的智能世界',
                      textAlign: TextAlign.center,
                      style: StylesUtils.customTextStyle(
                          fontSize: StylesUtils.fontSize12,
                          color: ColorsUtils.color6666,
                          lineHeight: 1.4.h),
                    ),
                  )
                ],
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.only(top: 20.h),
              padding: EdgeInsets.only(left: 35.w),
              color: Colors.white,
              alignment: Alignment.centerLeft,
              height: 40,
              child: Text(
                '品牌商品',
                style: StylesUtils.customTextStyle(
                    color: ColorsUtils.color3333,
                    fontSize: StylesUtils.fontSize13,
                    fontWeight: FontWeight.w700),
              ),
            ),
          ),
          Obx(() => SliverList.builder(
                itemBuilder: (BuildContext context, int index) {
                  var row = controller.pageList[index];
                  return Container(
                    decoration: const BoxDecoration(
                      color: Colors.white,
                    ),
                    padding: EdgeInsets.only(left: 15.w, right: 15.w, bottom: 15.h),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(5.r),
                          child: CachedNetworkImage(
                            imageUrl: row.imgUrl,
                            fit: BoxFit.fill,
                            width: 160,
                            height: 103,
                          ),
                        ),
                        Expanded(
                            child: Container(
                          padding: EdgeInsets.only(left: 10.w),
                          child: Column(
                            children: [
                              Container(
                                alignment: Alignment.topLeft,
                                child: Text(
                                  row.name,
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color3333, lineHeight: 1.3.h),
                                ),
                              ),
                              Container(
                                alignment: Alignment.centerLeft,
                                margin: EdgeInsets.only(top: 15.w),
                                child: Text(
                                  '￥${row.price}',
                                  style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.colorF95e,
                                  ),
                                ),
                              )
                            ],
                          ),
                        ))
                      ],
                    ),
                  );
                },
                itemCount: controller.pageList.length,
              )),
          Obx(() => loadMoreData())
        ],
      ),
    );
  }

  loadMoreData() {
    Widget child = Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 10.h),
      child: FractionallySizedBox(
          widthFactor: 0.9,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                margin: EdgeInsets.symmetric(horizontal: 10.w),
                alignment: Alignment.center,
                child: Text(
                  '我是有底线的',
                  style: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize13),
                ),
              ),
            ],
          )),
    );
    if (controller.isLoading.isTrue && controller.hasNext.isTrue) {
      child = Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 10.h),
        child: FractionallySizedBox(
            widthFactor: 0.8,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 10.w),
                  alignment: Alignment.center,
                  child: Text.rich(TextSpan(children: [
                    const WidgetSpan(
                        child: SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                          ),
                        ),
                        alignment: PlaceholderAlignment.middle),
                    TextSpan(
                        text: ' 数据加载中',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color9999))
                  ])),
                ),
              ],
            )),
      );
    } else if (controller.hasNext.isTrue) {
      child = Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 10.h),
        child: FractionallySizedBox(
            widthFactor: 0.9,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 10.w),
                  alignment: Alignment.center,
                  child: Text(
                    '上拉加载',
                    style: StylesUtils.customTextStyle(
                        color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize13),
                  ),
                ),
              ],
            )),
      );
    }
    return SliverToBoxAdapter(
      child: child,
    );
  }

  Color get activeBgColor {
    if (controller.isFollow.isTrue) {
      return ColorsUtils.rgba(255, 255, 255, 0);
    }
    return ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048);
  }

  TextStyle get activeStyle {
    if (controller.isFollow.isTrue) {
      return StylesUtils.customTextStyle(
        fontSize: StylesUtils.fontSize13,
          color: ColorsUtils.color8080
      );
    }
    return StylesUtils.customTextStyle(
        fontSize: StylesUtils.fontSize13);
  }
}
